angular.module('controllers',['ngPlugin'])
    .directive('tooltip',[function () {
        return {
            restrict:'EAC',
            scope: {
                min: '=',
                max: '=',
                title: '@',
            },
            link:function (scope,ele,attrs) {
                ele.tooltip({
                    placement:'top',
                    trigger:'focus',
                    title: scope.title?scope.title:'最小设置'+scope.min+',最大为'+scope.max
                });
            }
        }
    }])
    .controller('formController',['$scope','$timeout','tinymceConfig','notify','$http','$state','$stateParams','ngModal',function($scope,$timeout,tinymceConfig,notify,$http,$state,$stateParams,ngModal){
        function GetRequest() {
            var url = location.search; //获取url中"?"符后的字串
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=decodeURIComponent(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
        $scope.code_type = 1;
        $scope.code_type1 = 1;
        $scope.params = GetRequest();
        $scope.activity_id = $scope.params.activity_id||'';
        $scope.model_rule = $scope.params.model_rule;
        $scope.tabIndex = 1;//panel Index
        $scope.ruleTypes = [{
            value: 'day',
            text: '次/每日',
        },{
            value: 'all',
            text: '次/活动全程',
        }];
        //图片上传配置
        $scope.fileConfig = {
            config: {
                language: 'zh',
                maxFileCount: 1,
                maxFileSize: 200,
            },
        }
        //富文本配置
        $scope.tinymceOptions = angular.extend({},tinymceConfig,{
            setup : function(ed) {
                ed.on('blur', function(e) {
                    // console.log(tinymce.activeEditor.getContent());
                });
            }
        });
        $scope.postData = {
            name: '',
            category: $scope.params['category'],
            start_time: '',
            end_time: '',
            model_id: $scope.params['model_id'],
            template_id: $scope.params['template_id'],
            background_img:  '',
            list_background_img: '',
            remark: '',
            description: '',
            limits: {
                num: 1,
                type: 'day'
            },
            code_status:1,
            code_type:1,
            code:'',
            prize_id:'',
            inventory:'',
            rules: {
                type: 1,
                address: '',
                longitude: 0,
                latitude: 0,
                range: 100
            },
            shares: {
                isopen: 'off',
                title: '',
                content: '',
                thumb: ''
            }
        }
        // ================================================
        $scope.channel = {
            app: {
                is_open: 'off',
                app_urls: []
            },
            wechat: {
                is_open: 'off',
                qr_code: []
            }
        }
        $scope.isAuthorize = -1;//是否授权
        $scope.authorize = {};//授权信息
        function requestAuthorize(){
            $http({
                method:'get',
                url: '/web-api/configurations/wechat',
                headers: JSON.parse($('meta[name="profile"]').attr('content')),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
            }).success(function (data) {
                if (data.code == 200) {
                    if(data.data && data.data['app_id']&&data.data['app_secret']&&data.data['group_code']){
                        $scope.isAuthorize = 1;
                        $scope.authorize = data.data;
                    }else{
                        $scope.isAuthorize = 0;
                    }
                } else {
                    notify(data.message, 3);
                    $scope.isAuthorize = 0;
                }
            }).error(function (data) {
                notify(data.message, 3);
            });
        }
        requestAuthorize();
        function requestChannel(){
            $http({
                method:'get',
                url: '/web-api/publishing/'+$scope.activity_id,
                headers: JSON.parse($('meta[name="profile"]').attr('content')),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
            }).success(function (data) {
                if (data.code == 200) {
                    $scope.channel = {
                        app: {
                            is_open: data.data.app['is_open']?data.data.app['is_open']:'off',
                            app_urls: data.data.app['app_urls']?data.data.app['app_urls']:[]
                        },
                        wechat: {
                            is_open: data.data.wechat['is_open']?data.data.wechat['is_open']:'off',
                            qr_code: data.data.wechat['qr_code']?data.data.wechat['qr_code']:[]
                        }
                    }
                    $scope.refresh  = true;
                } else {
                    notify(data.message, 3);
                }
            }).error(function (data) {
                notify(data.message, 3);
            });
        }
        if($scope.activity_id){
            requestChannel();
        }
        function createChannel(callback){
            $http({
                method:'POST',
                url: '/web-api/publishing/'+$scope.activity_id,
                headers: JSON.parse($('meta[name="profile"]').attr('content')),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: $scope.channel
            }).success(function (data) {
                if (data.code == 200) {
                    callback();
                    // notify(data.message, 2);
                } else {
                    notify(data.message, 3);
                }
            }).error(function (data) {
                notify(data.message, 3);
            });
        }
        $scope.toggleClass = function($event,type){
            if($scope.isAuthorize!=1) {
                bootbox.confirm({
                    title: '提示:',
                    message: "您还未授权公众号，是否现在授权？<div class=\"checks\"><i>*</i>授权公众号后才可支持活动在微信端发布参与，授权后，用于授权的公众号将无法与其他三方应用平台对接</div>",
                    buttons: {
                        confirm: {
                            label: '确认',
                            className: 'btn-success'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-danger'
                        }
                    },
                    callback: function (result) {
                        if(result){
                            ngModal({
                                templateUrl: '/components/addSubscription.html',
                                controller: 'subscriptionModalController',
                                resolve: {
                                    items: function () {
                                        return {
                                            isAuthorize: $scope.isAuthorize,
                                            authorize: $scope.authorize
                                        };
                                    }
                                },
                                ok: function (authorize) {
                                    $scope.channel.wechat.is_open = 'on';
                                    $scope.isAuthorize = 1;
                                },
                                cancel: function () {

                                }
                            });
                        }
                    }
                });
            }else{
                if(type=='label'){
                    if($scope.channel.wechat['is_open']=='on'){
                        $scope.channel.wechat.is_open = 'off';
                    }else{
                        $scope.channel.wechat['is_open'] = 'on';
                    }
                }else{
                    $scope.channel.wechat['is_open'] = type;
                }
            }
        }
        // ================================================
        function requestActInfo(){
            $http({
                method: 'GET',
                url: '/web-api/activities/'+$scope.activity_id+'/'+$scope.params['model_rule'],
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                async: false,
            }).success(function(data){
                if(data.code==200){
                    $timeout(function(){
                        $scope.postData = {
                            name: data.data.name,
                            category: data.data.category,
                            start_time: data.data.start_time,
                            end_time: data.data.end_time,
                            model_id: data.data.model_id,
                            template_id: data.data.template_id,
                            background_img: data.data.background_img,
                            list_background_img: data.data.list_background_img,
                            app_url: data.data.app_url,
                            description:  data.data.description,
                            remark:data.data.remark,
                            limits: $.isEmptyObject(data.data.limits)?{
                                num: 1,
                                type: 'day'
                            }:data.data.limits,
                            code_status:data.data.code_status,
                            code_type:data.data.code_type,
                            code:data.data.code,
                            prize_id:data.data.prize_id,
                            inventory:data.data.inventory,
                            rules: $.isEmptyObject(data.data.rules)?{
                                is_spot: false,
                                address: '',
                                longitude: '',
                                latitude: '',
                                range: 100
                            }:data.data.rules,
                            shares: $.isEmptyObject(data.data.shares)?{
                                isopen: 'off',
                                title: '',
                                content: '',
                                thumb: ''
                            }:data.data.shares,
                        };
                        $scope.refresh = true;
                    },10);
                }else{
                    notify(data.message,3);
                }
            }).error(function(data){
                console.log(data);
            });
        }
        $scope.prizes = [];
        function requestBindPrizes(){
            $http({
                method: 'GET',
                url: '/web-api/'+$scope.params['model_rule']+'/'+$scope.activity_id+'/prizes',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                async: false,
                params: {per_page:1000,page:1},
            }).success(function(data){
                if(data.code==200){
                    $scope.prizes = data.data.data;
                    angular.forEach($scope.prizes,function(item,i){
                        item.winning_probability = item.winning_probability*100;
                    });
                }else{
                    notify(data.message,3);
                }
            }).error(function(data){
                console.log(data);
            });
        }
        //编辑
        if($scope.activity_id){
            requestActInfo();
            requestBindPrizes();
        }
        //切换tab
        $scope.toggleTab = function($event,index){
            if(!$scope.activity_id){
                notify('填写并保存内容设置',3);
            }else{
                $scope.tabIndex = index;
                $scope.refresh = true;
            }
        }
        var successCount = 0;
        function editRelatePrize(prize,index,callback){
            var newPrize = JSON.parse(JSON.stringify(prize));
            newPrize.winning_probability = newPrize.winning_probability/100;
            console.log(prize.id);
            console.log(prize.id?'/web-api/'+$scope.params['model_rule']+'/'+$scope.activity_id+'/prizes/'+prize.prize.id:'/web-api/'+$scope.params['model_rule']+'/'+$scope.activity_id+'/prize');
            $http({
                method: prize.id?'PATCH':'POST',
                url: prize.id?'/web-api/'+$scope.params['model_rule']+'/'+$scope.activity_id+'/prizes/'+prize.prize.id:'/web-api/'+$scope.params['model_rule']+'/'+$scope.activity_id+'/prize',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                async: false,
                data: newPrize,
            }).success(function(data){
                if(data.code==200){
                    successCount++;
                    if(!prize.id){
                        $scope.prizes[index].id = data.data.id;
                    }
                    if(successCount==$scope.prizes.length){
                        callback();
                        notify('保存成功',2);
                    }
                }else{
                    notify(data.message,3);
                }
            }).error(function(data){
                console.log(data);
            });
        }
        $scope.deletePrize = function($event,index,bindId,id){
            if(bindId){
                $http({
                    method: 'DELETE',
                    url: '/web-api/'+$scope.params['model_rule']+'/'+$scope.activity_id+'/prizes/'+id,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    async: false,
                }).success(function(data){
                    if(data.code==200){
                        $scope.prizes.splice(index,1);
                    }else{
                        notify(data.message,3);
                    }
                }).error(function(data){
                    console.log(data);
                });
            }else{
                $scope.prizes.splice(index,1);
            }
        }
        $scope.openListModal = function(){
            ngModal({
                templateUrl: '/components/prizeListModalContent.html',
                controller: 'listModalController',
                resolve: {
                    items: function(){
                        return {
                            prizes: $scope.prizes
                        };
                    }
                },
                ok: function(prize){
                    $scope.prizes.push({
                        prize_id: prize.id,
                        max_amount: '',
                        stock_limit: '',
                        winning_limit: '',
                        winning_probability: '',
                        img: prize.background_image,
                        availables: prize.availables,
                        prize: {
                            id: prize.id,
                            background_image: prize.background_image,
                            name: prize.name,
                            availables: prize.availables,
                        }
                    });
                },
                cancel: function(){

                }
            });
        }
        function validateData(){
            var validate = {
                msg: '',
                flag: false
            },keep=true,count=0;
            if(!$scope.postData.name){
                validate.msg = '请输入活动名称';
            }else if($scope.postData.name&&$scope.postData.name.length>20){
                validate.msg = '活动名称最多不超过20个字符';
            }else if(!$scope.postData.start_time){
                validate.msg = '开始时间不能为空';
            }else if(!$scope.postData.end_time){
                validate.msg = '结束时间不能为空';
            }else if($scope.postData.start_time>$scope.postData.end_time){
                validate.msg = '结束时间不能小于开始时间';
            }else if(!$scope.postData.remark){
                validate.msg = '活动备注信息不能为空';
            }else if(!$scope.postData.description){
                validate.msg = '活动简介或活动规则不能为空';
            }else if($scope.channel.app['is_open']=='on'&&$scope.channel.app.app_urls[0]&&!/^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test($scope.channel.app.app_urls[0])) {
                validate.msg = '请输入正确的链接（例如：http://www.chinamcloud.com）';
            }
            //else if(!$scope.postData.code_status){
            //    validate.msg = '请选择口令状态';
            //}else if(!$scope.postData.code_type){
            //    validate.msg = '请选择口令类型';
            //}else if(!$scope.postData.code){
            //    validate.msg = '请输入口令';
            //}else if(!$scope.postData.prize_id){
            //    validate.msg = '请选择奖品';
            //}else if(!$scope.postData.inventory){
            //    validate.msg = '请输入奖品库存';
            //}
            else if($scope.postData.shares.isopen=='on'){
                if(!$scope.postData.shares.title){
                    validate.msg = '分享标题不能为空';
                }else if(!$scope.postData.shares.content){
                    validate.msg = '分享内容不能为空';
                }else if(!$scope.postData.shares.thumb){
                    validate.msg = '分享图片不能为空';
                }else{
                    validate.flag = true;
                }
            }else{
                validate.flag = true;
            }
            if(validate.flag&&$scope.prizes.length>0){
                console.log($scope.prizes);
                angular.forEach($scope.prizes,function(item,i){
                    if(keep){
                        count += item.winning_probability;
                        if((item.stock_limit!=0&&!item.stock_limit)||item.stock_limit<0||item.stock_limit>item.availables){
                            validate.msg = '第'+(i+1)+'个奖项奖品库存验证不通过';
                            keep = false;
                            validate.flag = false;
                        }else if((item.winning_probability!=0&&!item.winning_probability) || item.winning_probability<0 || item.winning_probability>100){
                            validate.msg = '第'+(i+1)+'个奖项中奖概率验证不通过';
                            keep = false;
                            validate.flag = false;
                        }if($scope.model_rule=='roulette'&&(!item.alias_name||(item.alias_name&&item.alias_name.length>4))){
                            validate.msg = '第'+(i+1)+'个奖项展示名验证不通过';
                            keep = false;
                            validate.flag = false;
                        }
                    }
                });
                if(validate.flag && count>100){
                    validate.msg = '中奖概率总和不能超过100';
                }
            }
            return validate;
        }
        $scope.default = function(){}
        //提交活动
        $scope.submit = function($event,callback){
            var $btn = angular.element($event.target);
            if(!$btn.hasClass('disabled')){
                var validate = validateData();
                if(!validate.flag){
                    notify(validate.msg,3);
                }else{
                    $btn.addClass('disabled');
                    $http({
                        method:$scope.activity_id?'PATCH':'POST',
                        url:$scope.activity_id?'/web-api/activities/'+$scope.activity_id+'/guess-code':'/web-api/activities/guess-code',
                        headers:  JSON.parse($('meta[name="profile"]').attr('content')),
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        data: $scope.postData,
                    }).success(function(data){
                        $btn.removeClass('disabled');
                        if(data.code==200){
                            if($scope.tabIndex==1) {
                                $scope.tabIndex = 2;
                            }
                            if(!$scope.activity_id){
                                $scope.activity_id = data.data.id;
                            }else{
                                if($scope.prizes.length==0){
                                    callback();
                                }else{
                                    successCount = 0;
                                    angular.forEach($scope.prizes,function(item,index){
                                        editRelatePrize(item,index,callback);
                                    });
                                }
                            }
                        }else{
                            notify(data.message,3);
                        }
                    }).error(function(data){
                        $btn.removeClass('disabled');
                        notify(data.message,3);
                    });
                }
            }
        };
        //返回
        $scope.goBack = function($event){
            window.history.go(-1);
        }
        //完成
        $scope.complete = function($event){
            $scope.submit(angular.element($event.target),function(){
                createChannel(function(){
                    location.href = '/web/activity/index';
                });
            });
        }
        //===============================================end of all
        function initpreview(){
            if($scope.model_rule=='roulette'){
                // 转盘区域
                var turnplate = {
                    restaraunts: [], //大转盘奖品名称
                    colors: [], //大转盘奖品区块对应背景颜色
                    outsideRadius: 178, //大转盘外圆的半径
                    textRadius: 115, //大转盘奖品位置距离圆心的距离
                    insideRadius: 46, //大转盘内圆的半径
                    startAngle: 0, //开始角度
                    bRotate: false //false:停止;ture:旋转
                };
                var colors = ["#FEEF9D", "#FFDD76"];
                function Turnplate(prizes){
                    var array = JSON.parse(JSON.stringify(prizes));
                    array.unshift('谢谢参与');

                    var str = '谢谢参与';
                    switch(prizes.length){
                        case 1:
                            turnplate.restaraunts = Array.prototype.concat(array,array,array);
                            break;
                        case 2:
                            turnplate.restaraunts = Array.prototype.concat(array,array);
                            break;
                        case 3:
                            turnplate.restaraunts = Array.prototype.concat(array,array);
                            break;
                        case 4:
                            turnplate.restaraunts = Array.prototype.concat(array.slice(0,3),[str],array.slice(3,5));
                            break;
                        case 5:
                            turnplate.restaraunts = array;
                            break;
                    }
                    if(turnplate.restaraunts.length==6){
                        turnplate.colors =  Array.prototype.concat(colors,colors,colors);
                        turnplate.startAngle = Math.PI*(60/360);
                    }else if(turnplate.restaraunts.length==8){
                        turnplate.colors =  Array.prototype.concat(colors,colors,colors,colors);
                    }
                    console.log(turnplate.restaraunts);
                    //页面所有元素加载完毕后执行drawRouletteWheel()方法对转盘进行渲染
                    drawRouletteWheel();
                }
                function drawRouletteWheel() {
                    var canvas = document.getElementById("wheelcanvas");
                    if (canvas.getContext) {
                        //根据奖品个数计算圆周角度
                        var arc = Math.PI / (turnplate.restaraunts.length / 2);
                        var ctx = canvas.getContext("2d");
                        //在给定矩形内清空一个矩形
                        //ctx.clearRect(0,0,422,422);
                        //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式
                        ctx.strokeStyle = "#FFBE04";
                        //font 属性设置或返回画布上文本内容的当前字体属性
                        ctx.font = '16px Microsoft YaHei';
                        for (var i = 0; i < turnplate.restaraunts.length; i++) {
                            var angle = turnplate.startAngle + i * arc;
                            ctx.fillStyle = turnplate.colors[i];
                            ctx.beginPath();
                            //arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线（用于创建圆或部分圆）
                            ctx.arc(211, 211, turnplate.outsideRadius, angle, angle + arc, false);
                            ctx.arc(211, 211, turnplate.insideRadius, angle + arc, angle, true);
                            ctx.stroke();
                            ctx.fill();
                            //锁画布(为了保存之前的画布状态)
                            ctx.save();

                            //----绘制奖品开始----
                            ctx.fillStyle = "#fff";
                            var text_allin = turnplate.restaraunts;
                            // console.log(text_allin.indexOf("8"));
                            var text = turnplate.restaraunts[i];
                            var line_height = 17;
                            //translate方法重新映射画布上的 (0,0) 位置
                            ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius);
                            // console.log((angle + arc / 2 + Math.PI / 2));
                            //rotate方法旋转当前的绘图
                            ctx.rotate(angle + arc / 2 + Math.PI / 2 - 1.64); //-1.64定位

                            /** 下面代码根据奖品类型、奖品名称长度渲染不同效果，如字体、颜色、图片效果。(具体根据实际情况改变) **/
                            ctx.fillStyle = "#BC6619";
                            ctx.textAlign = "center";
                            if(turnplate.restaraunts.length==6){
                                ctx.rotate(90* Math.PI/180);
                                ctx.font = 'bold 24px Microsoft YaHei';
                                ctx.fillText(text, 0, 0);
                            }else if(turnplate.restaraunts.length==8){
                                ctx.font = 'bold 24px Microsoft YaHei';
                                ctx.fillText(text, 0, 8);
                            }
                            //把当前画布返回（调整）到上一个save()状态之前
                            ctx.restore();
                            //----绘制奖品结束----
                        }
                    }
                }
                var alias_nameArray = [];
                $scope.$watch('prizes',function(){
                    alias_nameArray = [];
                    for(var i=0;i<$scope.prizes.length;i++){
                        alias_nameArray.push($scope.prizes[i].alias_name?$scope.prizes[i].alias_name:'');
                    }
                    Turnplate(alias_nameArray);
                },true);
            }
        }
        initpreview();
    }])
    .controller('listModalController',['$scope','$timeout','$http','$modalInstance','notify','items',function ($scope,$timeout,$http,$modalInstance,notify,items) {
        $scope.pramas = {per_page:8,page:1,q:''};
        $scope.query = '';
        $scope.prizes = [];
        $scope.areadyPrizes = items.prizes;
        $scope.numbers = [1];
        $scope.httpData = {};
        function requestList(){
            $http({
                method: 'GET',
                url: '/web-api/prizes/available',
                dataType: 'json',
                contentType: "application/json",
                params: $scope.pramas,
            }).success(function(data){
                if(data.code==200){
                    $scope.httpData = data.data;
                    $scope.prizes = data.data.data;
                    angular.forEach($scope.prizes,function(prize,i){
                        angular.forEach($scope.areadyPrizes,function(item,j){
                            if(item.prize_id == prize.id){
                                $timeout(function(){
                                    $scope.prizes[i].disabled = true;
                                },10);
                            }else{
                                $scope.prizes[i].disabled = false;
                            }
                        });
                    });
                    if(data.data.last_page>0){
                        $scope.numbers = [];
                        for(var i=1;i<=data.data.last_page;i++){
                            $scope.numbers.push(i);
                        }
                    }
                }else{
                    notify(data.message,4);
                }
            }).error(function(data){
                notify('网络异常，稍后重试!',4);
                console.log(data);
            });
        }
        requestList();
        $scope.selected = '';
        $scope.selectedPrize = function(event,prize){
            $scope.selected = prize;
        }
        $scope.jumpPage = function(index){
            $scope.pramas.page = index;
            requestList();
        }
        $scope.serach = function($event){
            $scope.pramas.q = $scope.query;
            requestList();
        }
        $scope.ok = function ($event) {
            if(!$scope.selected){
                notify('请选择奖品',2);
            }else{
                $modalInstance.close($scope.selected);
            }
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    }])
    .controller('subscriptionModalController',['$scope','$timeout','$http','$modalInstance','notify','items',function ($scope,$timeout,$http,$modalInstance,notify,items) {
        var profile = JSON.parse($('meta[name="profile"]').attr('content'));
        if(items.isAuthorize==1){
            $scope.postData = items.authorize;
        }else{
            $scope.postData = {
                app_id: '',
                app_secret: '',
                group_code: profile.group_code,
            }
        }
        $scope.ok = function ($event) {
            if(!$scope.postData.app_id){
                notify('APP_ID不能为空', 3);
                return;
            }
            if(!$scope.postData.app_secret){
                notify('SecurityKey不能为空', 3);
                return;
            }
            var $btn = angular.element($event.target).addClass('disabled');
            $http({
                method:items.isAuthorize==1?'PATCH':'POST',
                url: '/web-api/configurations/wechat',
                headers: JSON.parse($('meta[name="profile"]').attr('content')),
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: $scope.postData,
            }).success(function (data) {
                $btn.removeClass('disabled');
                if (data.code == 200) {
                    if(items.isAuthorize==0){
                        notify('授权成功', 2);
                    }else{
                        notify('修改成功', 2);
                    }
                    $modalInstance.close($scope.postData);
                } else {
                    notify(data.message, 3);
                }
            }).error(function (data) {
                $btn.removeClass('disabled');
                notify(data.message, 3);
            });
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    }]);
